// import { Button, Dropdown, Menu} from 'antd';
import { AddMenu, DelMenu, GetMenuByPage, GetMenuTree, updateMenu } from '@/services/system/menu';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';

import { Button, Form, Input, message, Modal, Tree } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

const Menu: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [rowData, setRowData] = useState({ id: '' }); // 保存行值

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([
    '402881e581f6ca830181f6caa70f0003',
    '0-0-1',
  ]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['0-0-0']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  // const [parentId, setParentId] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [treeData, setTreeData] = useState([{ title: '菜单树', key: '0-0', children: [] }]);
  const [form] = Form.useForm();

  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [formTitle, setFormTitle] = useState('新建菜单'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '权限编码', //表头显示的名称
      dataIndex: 'code', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '名称', //表头显示的名称
      dataIndex: 'name', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '序列',
      search: false,
      dataIndex: 'seq',
      //   filters: [      // 表头的筛选菜单项
      //     { text: '个人', value: '个人' },
      //     { text: '一般纳税人', value: '一般纳税人' },
      //   ],
    },
    {
      title: '类型',
      search: false,
      dataIndex: 'type',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑菜单');
            form.setFieldsValue({
              name: record.name,
              code: record.code,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除菜单',
              content: '确定删除菜单吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await DelMenu({ id: record.id });
                actionRef.current.reload();
              },
            });
            // actionRef.current.reload();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  useEffect(() => {
    // Using an IIFE
    (async () => {
      const result = await GetMenuTree();
      setTreeData(result.data);
      setExpandedKeys(['402881e581f6ca830181f6caa70f0003']);
    })();
  }, []);

  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(true);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', selectedKeysValue);
    setSelectedKeys(selectedKeysValue);
    actionRef.current.reload();
  };

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建菜单') {
      const result = await AddMenu({ ...form.getFieldsValue(), parentId: selectedKeys[0] });

      // 重新请求树形表单重新赋值
      const result1 = await GetMenuTree();
      setTreeData(result1.data);
      if (result != null) {
        message.success('添加成功');
      }
      // message.success('添加成功');
    } else {
      await updateMenu(form.getFieldsValue());
      const result1 = await GetMenuTree();
      setTreeData(result1.data);
    }
    //message.success('添加成功');
    setConfirmLoading(false);
    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
    // setModalVisit(false);
    // // 这个爆红不用管(从新加载页面)
    // actionRef.current.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      {/* <Row> */}
      {/* <Col span={4}>
          <Tree
            checkable
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={true}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            onSelect={onSelect}
            defaultExpandAll={true}
            selectedKeys={selectedKeys}
            treeData={treeData}
          />
        </Col> */}
      {/* <Col span={20}> */}
      <ProTable //表格Pro组件
        headerTitle="菜单查询" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              // console.log(selectedRows, '---选取多行----');
              // 1.清空form
              setCreateOrUpdate(false);
              setFormTitle('新建菜单');
              form.resetFields();
              //
              setModalVisit(true);
            }}
            type="primary"
          >
            新建菜单
          </Button>,
        ]}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <Tree
              checkable
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={true}
              onCheck={onCheck}
              checkedKeys={checkedKeys}
              onSelect={onSelect}
              defaultExpandAll={true}
              selectedKeys={selectedKeys}
              treeData={treeData}
            />
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          const result = await GetMenuByPage({ ...params, parentId: selectedKeys[0] });
          return {
            data: result?.data?.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        columns={columns} //上面定义的
        rowSelection={{}}
      />
      {/* </Col>
      </Row> */}
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="编码"
            name="code"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>

          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default Menu;
